const db = wx.cloud.database()
// 定义城市、天气、温度、风级、图片,日期参数
var getcity, getweather, gettemp, getwind, getpic, getdate
var ak = '' // 在此处填写申请到的ak
var url_now = ''
var url_forecast = ''
var url_city = ''
var latitude, longitude

Page({
  data: {},
  // 初始化加载
  onLoad: function (e) {
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        latitude = res.latitude
        longitude = res.longitude
        // 查询参数
        db.collection("parameter")
          .where({
            name: '风和天气'
          })
          .get()
          .then(res => {
            url_now = res.data[0].url_now
            url_forecast = res.data[0].url_forecast
            url_city = res.data[0].url_city
            ak = res.data[0].ak
            // 默认城市名称
            wx.request({
              url: url_city + '&location=' + longitude + ',' + latitude + '&key=' + ak,
              success: function (res) {
                if (!res.data.location) {
                  console.log('获取地理位置接口失败')
                  return
                }
                getcity = res.data.location[0].name
                that.weather()
              }
            })
          })
          .catch(err => {
            console.error(err)
          })
      },
      fail: function () {
        wx.hideLoading();
        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              wx.showModal({
                title: '',
                content: '请允许老黄狗工具箱获取您的定位',
                confirmText: '授权',
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting();
                  } else {
                    console.log('get location fail');
                  }
                }
              })
            } else {
              //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位
              wx.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function (res) {
                }
              })
            }
          }
        })
      }
    })
  },
  // 动态获取input输入值 城市名称
  bindKeyInput: function (e) {
    getcity = e.detail.value
  },
  // 搜索城市
  search: function () {
    wx.showLoading({
      title: '加载中',
    })
    let that = this
    wx.request({
      url: url_city + '&location=' + getcity + '&key=' + ak,
      success: function (res) {
        // console.log(res)
        if (!res.data.location) {
          console.log('获取地理位置接口失败')
          wx.hideLoading()
          wx.showToast({ title: '查无此城市', icon: 'error', mask: true })
          return
        }
        latitude = res.data.location[0].lat
        longitude = res.data.location[0].lon
        getcity = res.data.location[0].name
        that.weather()
      },
      fail: function () {
        wx.hideLoading()
      }
    })
  },
  weather: function () {
    let that = this
    wx.request({
      url: url_now + '&location=' + longitude + ',' + latitude + '&key=' + ak,
      success: function (res) {
        // console.log(res.data.now)
        if (!res.data.now) {
          console.log('获取天气接口失败')
          return
        }
        getweather = res.data.now.text
        gettemp = res.data.now.temp
        getwind = res.data.now.windDir + ' ' + res.data.now.windScale + '级'
        getpic = res.data.now.icon
        let temp = res.data.now.obsTime.split("T")
        getdate = temp[0] + ' ' + temp[1].split("+")[0]
        that.setData({
          city: getcity,
          weather: getweather,
          temp: gettemp + '°',
          wind: getwind,
          pic: '../../images/weather/' + getpic + '.png',
          date: getdate
        })
        wx.hideLoading()
      }
    })
    wx.request({
      url: url_forecast + '&location=' + longitude + ',' + latitude + '&key=' + ak,
      success: function (res) {
        // console.log(res.data)
        if (!res.data.daily) {
          console.log('获取3天天气接口失败')
          return
        }
        let forecastData = [];
        let result = res.data.daily
        let getFxDate = ''
        for (let i = 0; i < result.length; i++) {
          if (i == 0) {
            getFxDate = '今天 ' + result[i].fxDate
          } else if (i == 1) {
            getFxDate = '明天 ' + result[i].fxDate
          } else {
            getFxDate = '后天 ' + result[i].fxDate
          }
          forecastData.push({ "fxDate": getFxDate, "textDay": result[i].textDay, "temp": result[i].tempMin + '°~' + result[i].tempMax + '°' });
        }
        that.setData({ forecastData })
        wx.hideLoading()
      }
    })
  },
  queryParameter() {
    db.collection("parameter")
      .where({
        name: '风和天气'
      })
      .get()
      .then(res => {
        url_now = res.data.url_now
        url_city = res.data.url_city
        ak = res.data.ak
      })
      .catch(err => {
        console.error(err)
      })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '未雨绸缪!!!',
      // path: '/pages/air-conditioner/air-conditioner'
    }
  }
})